﻿using EnglishAuction.BUS;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace EnglishAuction
{
    public partial class ManageUser : System.Web.UI.Page
    {
        private int? EditUserId
        {
            get
            {
                return (int?)ViewState["EditUserId"];
            }

            set
            {
                ViewState["EditUserId"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            txtError.Text = "";
            txtError.ForeColor = Color.Red;
            txtError.Font.Bold = true;
            txtCMND.Attributes.Add("onkeypress", "return isNumberKey(event)");
            txtSoDienThoai.Attributes.Add("onkeypress", "return isNumberKey(event)");
            if (!Page.IsPostBack)
            {
                LoadListUser();
            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (NguoiDungBUS.CheckEmail(txtEmail.Text.Trim(), EditUserId.Value))
            {
                txtError.Text = "- Email này đã có người sử dụng.";
                return;
            }
            else if (NguoiDungBUS.CheckCMND(txtCMND.Text.Trim(), EditUserId.Value))
            {
                txtError.Text = "- CMND này đã có người sử dụng.";
                return;
            }
            else
            {
                var nguoiDung = NguoiDungBUS.GetById(EditUserId.Value);
                nguoiDung.HoTen = txtHoTen.Text;
                nguoiDung.GioiTinh = rbNam.Checked ? true : false;
                nguoiDung.SoDienThoai = txtSoDienThoai.Text;
                nguoiDung.NgaySinh = DateTime.Parse(txtNgaySinh.Text.Trim());
                nguoiDung.Email = txtEmail.Text;
                nguoiDung.CMND = txtCMND.Text;
                nguoiDung.DiaChi = txtDiaChi.Text;
                NguoiDungBUS.Update(nguoiDung);

                HideEditCustomer();
                //LoadListUser();
                TriggerClientGridRefresh();
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            HideEditCustomer();
        }

        protected void gvNguoiDung_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem == null)
                return;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label type = (Label)e.Row.FindControl("lbLoaiNguoiDung");
                if (type.Text == "1")
                {
                    type.Text = "Người bán";
                }

                else if (type.Text == "2")
                {
                    type.Text = "Người mua";
                }
            }
            ImageButton btnEdit = (ImageButton)e.Row.FindControl("btnUpdate");
            btnEdit.OnClientClick = "openDialogAndBlock('Cập nhật thông tin người dùng', '" + btnEdit.ClientID + "')";
        }

        protected void gvNguoiDung_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int userId = Convert.ToInt32(e.CommandArgument);

            switch (e.CommandName)
            {
                //Can't use just Edit and Delete or need to bypass RowEditing and Deleting
                case "UpdateUser":
                    FillDataToDialog(userId);
                    this.EditUserId = userId;
                    Thread.Sleep(1000);
                    RegisterStartupScriptCommand("jsUnblockDialog", "unblockDialog();");
                    //Setting timer to test longer loading
                    break;

                case "DeleteUser":
                    //GridDataBind();
                    break;
                case "ResetUser":
                    string newPass = Utilities.GeneratePassword(6);
                    NguoiDungBUS.ResetPassword(userId, Utilities.GetMD5Hash(newPass));
                    Utilities.SendMail(NguoiDungBUS.GetById(userId).Email, String.Format("Mật khẩu mới: {0}", newPass));
                    RegisterStartupScriptCommand("jsUnblockDialog", "alert('Cấp lại mật khẩu thành công.');");
                    break;
            }
        }

        protected void LoadListUser()
        {
            gvNguoiDung.DataSource = NguoiDungBUS.GetAll();
            gvNguoiDung.DataBind();
        }

        private void FillDataToDialog(int id)
        {
            NguoiDung nguoiDung = NguoiDungBUS.GetById(id);
            txtTenTaiKhoan.Text = nguoiDung.TaiKhoan;
            txtSoDienThoai.Text = nguoiDung.SoDienThoai;
            txtHoTen.Text = nguoiDung.HoTen;
            txtNgaySinh.Text = String.Format("{0:MM/dd/yyyy}", nguoiDung.NgaySinh.Value);
            txtDiaChi.Text = nguoiDung.DiaChi;
            txtEmail.Text = nguoiDung.Email;
            txtCMND.Text = nguoiDung.CMND;
            if (nguoiDung.GioiTinh.Value)
                rbNam.Checked = true;
            else
                rbNu.Checked = true;
        }

        private void RegisterStartupScriptCommand(string key, string script)
        {
            ScriptManager.RegisterStartupScript(phrJsRunner, phrJsRunner.GetType(), key, script, true);
        }

        private void HideEditCustomer()
        {
            //ClearEditCustomerForm();
            RegisterStartupScriptCommand("jsCloseDialg", "closeDialog();");
        }

        protected void btnRefreshGrid_Click(object sender, EventArgs e)
        {
            LoadListUser();
        }

        private void TriggerClientGridRefresh()
        {
            string script = "__doPostBack(\"" + btnRefreshGrid.ClientID + "\", \"\");";
            RegisterStartupScriptCommand("jsGridRefresh", script);
            LoadListUser();
        }
    }
}